package com.yjh.study.data.structure.stack;

import com.yjh.study.data.structure.LinkedElement;
import com.yjh.study.data.structure.list.LinkedList;

import java.util.Iterator;

public class LinkedStack<T> implements Stack<T> {

    private final InnerList<T> innerList;

    public LinkedStack() {
        this.innerList = new InnerList<>();
    }

    private int size;

    @Override
    public int size() {
        return innerList.size();
    }

    @Override
    public boolean isEmpty() {
        return innerList.size() <= 0;
    }

    @Override
    public void add(T t) {
        push(t);
    }

    @Override
    public void remove(T t) {
        throw new RuntimeException("非法操作");
    }

    @Override
    public void clear() {
        this.innerList.clear();
    }

    @Override
    public T top() {
        return this.innerList.getFirst();
    }

    @Override
    public T pickOut() {
        return this.innerList.pickFirst();
    }

    @Override
    public void push(T t) {
        this.innerList.addFirst(t);
    }

    @Override
    public Iterator<T> iterator() {
        return this.innerList.iterator();
    }

    protected static class InnerList<T> extends LinkedList<T> {
        T pickFirst() {
            LinkedElement<T> firstElement = this.header.getNext();
            remove(firstElement);
            return firstElement.getData();
        }
    }

}
